/**
*
*/
package com.bestdo.t;

import static java.nio.file.StandardWatchEventKinds.ENTRY_DELETE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.StringUtils;

/**
 * @Title SensitiveWordUtil.java
 * @Copyright 2014 (c)
 * @Description: 敏感词过滤 <br>
 * @Company: anzhi.com
 * @Created on 2014年9月9日 上午11:23:00
 * @author liuhui@anzhi.com
 * @version 1.0
 */
public class SensitiveWordUtil {
	private static final String DIC_PATH = "sensitiveWord.dic";
	private static final String CHARSET = "utf-8";

	public static Map<Object, Object> sensitiveWordMap = new HashMap<>();

	static {
		try {
			initDic();
			startFileListener();
		} catch (Exception e) {
			throw new ExceptionInInitializerError(e);
		}
	}

	/**
	 * @Description:初始化词典
	 * @Date: 2014年9月9日 上午11:23:51
	 * @author liuhui@anzhi.com void
	 * @throws IOException
	 */
	@SuppressWarnings("unchecked")
	private static void initDic() throws IOException {
		sensitiveWordMap.clear();
		Map<Object, Object> nowMap = null;
		Map<Object, Object> newWorMap = null;
		try (BufferedReader br = new BufferedReader(new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream(DIC_PATH), CHARSET))) {
			while (true) {
				String line = br.readLine();
				if (line == null) {
					break;
				}
				if (StringUtils.isBlank(line)) {
					continue;
				}
				nowMap = sensitiveWordMap;
				for (int i = 0; i < line.length(); i++) {
					char keyChar = line.toLowerCase().charAt(i); // 转换成char型
					Object wordMap = nowMap.get(keyChar); // 获取
					if (wordMap != null) { // 如果存在该key，直接赋值
						nowMap = (Map<Object, Object>) wordMap;
					} else { // 不存在则，则构建一个map，同时将isEnd设置为0，因为他不是最后一个
						newWorMap = new HashMap<>();
						newWorMap.put("isEnd", "0"); // 不是最后一个
						nowMap.put(keyChar, newWorMap);
						nowMap = newWorMap;
					}
					if (i == line.length() - 1) {
						nowMap.put("isEnd", "1"); // 最后一个
					}
				}
			}
		}

	}

	/**
	 * @Description:启动敏感字典文件监控
	 * @Date: 2014年9月9日 上午11:28:06
	 * @author liuhui@anzhi.com void
	 * @throws Exception
	 */
	private static void startFileListener() throws Exception {
		new Thread() {
			public void run() {
				try {
					Path dic = Paths.get(Thread.currentThread().getContextClassLoader().getResource(DIC_PATH).toURI()).getParent();
					WatchService watcher = FileSystems.getDefault().newWatchService();
					dic.register(watcher, ENTRY_DELETE, ENTRY_MODIFY);
					WatchKey watckKey = watcher.take();
					List<WatchEvent<?>> events = watckKey.pollEvents();

					for (WatchEvent<?> event : events) {
						Path p = (Path) event.context();
						if (DIC_PATH.equals(p.toString())) {
							initDic();
						}
					}
					startFileListener();
				} catch (Exception e) {
					throw new RuntimeException(e);
				}
			};
		}.start();
	}

	/**
	 * 检查文字中是否包含敏感字符，检查规则如下：<br>
	 * 
	 * @param txt
	 * @param beginIndex
	 * @param matchType
	 * @return，如果存在，则返回敏感词字符的长度，不存在返回0
	 * @version 1.0
	 */
	@SuppressWarnings("unchecked")
	public static int checkSensitiveWord(String txt, int beginIndex, boolean fullMatch) {
		txt = txt.replaceAll(" ", "");
		boolean flag = false; // 敏感词结束标识位：用于敏感词只有1位的情况
		int matchFlag = 0; // 匹配标识数默认为0
		char word = 0;
		Map<Object, Object> nowMap = sensitiveWordMap;
		for (int i = beginIndex; i < txt.length(); i++) {
			word = txt.charAt(i);
			nowMap = (Map<Object, Object>) nowMap.get(word); // 获取指定key
			if (nowMap != null) { // 存在，则判断是否为最后一个
				matchFlag++; // 找到相应key，匹配标识+1
				if ("1".equals(nowMap.get("isEnd"))) { // 如果为最后一个匹配规则,结束循环，返回匹配标识数
					flag = true; // 结束标志位为true
					if (!fullMatch) {
						break;
					}
				}
			} else { // 不存在，直接返回
				break;
			}
		}
		if (matchFlag < 2 || !flag) { // 长度必须大于等于1，为词
			matchFlag = 0;
		}
		return matchFlag;
	}

	public static boolean hasSensitiveWord(String txt) {
		boolean flag = false;
		if (StringUtils.isBlank(txt))
			return flag;
		txt = txt.toLowerCase();
		for (int i = 0; i < txt.length(); i++) {
			int matchFlag = checkSensitiveWord(txt, i, false); // 判断是否包含敏感字符
			if (matchFlag > 0) { // 大于0存在，返回true
				flag = true;
			}
		}
		return flag;
	}

	/**
	 * 获取文字中的敏感词
	 * 
	 * @author chenming
	 * @date 2014年4月20日 下午5:10:52
	 * @param txt
	 *            文字
	 * @param matchType
	 *            匹配规则&nbsp;1：最小匹配规则，2：最大匹配规则
	 * @return
	 * @version 1.0
	 */
	public static Set<String> getSensitiveWord(String txt) {
		txt = txt.replaceAll(" ", "");
		Set<String> sensitiveWordList = new HashSet<String>();

		for (int i = 0; i < txt.length(); i++) {
			int length = checkSensitiveWord(txt, i, true); // 判断是否包含敏感字符
			if (length > 0) { // 存在,加入list中
				sensitiveWordList.add(txt.substring(i, i + length));
				i = i + length - 1; // 减1的原因，是因为for会自增
			}
		}

		return sensitiveWordList;
	}

	/**
	 * 替换敏感字字符
	 * 
	 * @author chenming
	 * @date 2014年4月20日 下午5:12:07
	 * @param txt
	 * @param matchType
	 * @param replaceChar
	 *            替换字符，默认*
	 * @version 1.0
	 */
	public static String replaceSensitiveWord(String txt, boolean fullMatch, String replaceChar) {
		String resultTxt = txt;
		Set<String> set = getSensitiveWord(txt); // 获取所有的敏感词
		Iterator<String> iterator = set.iterator();
		String word = null;
		String replaceString = null;
		while (iterator.hasNext()) {
			word = iterator.next();
			replaceString = getReplaceChars(replaceChar, word.length());
			resultTxt = resultTxt.replaceAll(word, replaceString);
		}
		return resultTxt;
	}

	/**
	 * 获取替换字符串
	 * 
	 * @author chenming
	 * @date 2014年4月20日 下午5:21:19
	 * @param replaceChar
	 * @param length
	 * @return
	 * @version 1.0
	 */
	private static String getReplaceChars(String replaceChar, int length) {
		String resultReplace = replaceChar;
		for (int i = 1; i < length; i++) {
			resultReplace += replaceChar;
		}

		return resultReplace;
	}

	public static void main(String[] args) throws InterruptedException {
		try {
			SensitiveWordUtil.initDic();
			boolean ret = SensitiveWordUtil.hasSensitiveWord("aebfg");
			System.out.println(ret);
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
}
